#!/usr/bin/env python
# -*- coding: UTF-8 -*-

'''
关键字对比过滤/转换

usage:
contrast = {
                    'tid'           :   'tid',
                    'company_code'  :   'company_code',
                    'sender_id'     :   'sender_id',
                    'cancel_id'     :   'cancel_id',
                    'logistics_no'  :   'out_sid'
                }
data = {
        'logistics_no':'ttttt',
        'test':'demo'
    }
contrast_convert(contrast,data)
result：{'out_sid': 'ttttt'}
'''
def contrast_convert(contrast,data,empty_retain=False) :
    result = {}
    from_keys = contrast.keys()
    for key in from_keys :
        value = data if not isinstance(data,dict) else data.get(key,'')
        to_key = contrast.get(key,'')

        if isinstance(value,(dict,list,tuple)) :
            (to_key,to_contrast) = to_key.popitem()
        
        if isinstance(value,dict) :
            result[to_key] = contrast_convert(to_contrast,value,empty_retain)
        elif isinstance(value,(list,tuple)) :
            result[to_key] = []
            for item in value :
                tmp = contrast_convert(to_contrast,item,empty_retain)
                result[to_key].append(tmp)
        elif to_key and (empty_retain or (not empty_retain and value)) :
            result[to_key] = value
    return result

if __name__ == '__main__' :

    contrast = {
                        'tid'           :   'tid',
                        'company_code'  :   'company_code',
                        'sender_id'     :   'sender_id',
                        'cancel_id'     :   'cancel_id',
                        'logistics_no'  :   'out_sid',
                        'product'       :   {
                            'items' : {
                            'skuCode1'   :   'item_code',
                            'skuCode2'   :   'item_code2',
                            }
                        },
                        'test'       :   {
                            'demo' : {
                            'demo1'   :   'item_demo1',
                            'demo2'   :   'item_demo2',
                            }
                        },
                    }
    data = {
            'logistics_no':'ttttt',
            'test':{
                'demo1':'qqq',
                'demo3':'www',
             },
            'product':[
                {
                'skuCode1':'111',
                'skuCode2':'222',
                },
                {
                'skuCode1':'333',
                'skuCode2':'444',
                },
                {
                'skuCode1':'555',
                'skuCode2':'666',
                },
            ]
        }
    print contrast_convert(contrast,data)
